from contextlib import contextmanager
from redis import Redis
from redlock import RedLock


@contextmanager
def worker_lock_manager(key, ttl, **kwargs):
    """
    分布式锁
    :param key: 分布式锁ID
    :param ttl: 分布式锁生存时间
    :param kwargs: 可选参数字典
    :return: None
    """
    redis_servers = [{
        'host': '127.0.0.1',
        'port': 6379,
        'db': 0
    }]

    rlk = RedLock(redis_servers)
    # 获取锁
    lock = rlk.lock(key, ttl)
    
    yield lock

    # 释放锁
    rlk.unlock(lock)

client = Redis()


def add():
    with worker_lock_manager('unique_key', 1000) as w_lock:
        if w_lock is False:
            value = int(client.get('unique_key')) + 1
            client.set('unique_key', value)
            return

import threading


if __name__ == '__main__':
    threads = []
    for i in range(100000):
        a = threading.Thread(target=add)
        threads.append(a)
    for i in threads:
        i.start()
    for i in threads:
        i.join()
    value = client.get('unique_key')
    print(value)